<template>
  <div class="container">
    <!-- 路径导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>内容管理</el-breadcrumb-item>
      <el-breadcrumb-item>课程管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索区域 -->
    <el-row>
      <el-form :inline="true">
        <el-form-item label="课程名称" style="margin-right: 20px">
          <el-input v-model="queryInfo.courseName" clearable @clear.capture="queryList" placeholder="请课程名称"></el-input>
        </el-form-item>
        <el-form-item label="课程类型" style="margin-right: 20px">
          <el-select v-model="queryInfo.typeId" placeholder="请选择" clearable @clear.capture="queryList">
            <el-option v-for="item in courseTypeList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="咨询师" style="margin-right: 20px">
          <el-select v-model="queryInfo.teacherId" placeholder="请选择" clearable @clear.capture="queryList">
            <el-option v-for="item in consultList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="queryList">搜索</el-button>
          <el-button type="success" icon="el-icon-plus" @click="addCourse">新增课程</el-button>
        </el-form-item>
      </el-form>
    </el-row>



    <!-- 表格区域 -->
    <el-table :data="courseList" border style="width: 100%" :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }">
      <el-table-column width="80px" prop="id" label="ID" />
      <el-table-column prop="courseName" label="课程名称" />
      <el-table-column prop="tabularChart" width="130" label="课程图片">
        <template slot-scope="scope">
          <el-image style="width: 100px; height: 100px;"
            :src="url + 'downLoad?filename=' + scope.row.tabularChart"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="couseTime" label="课程时长" />

      <el-table-column prop="courseMount" label="课程数量" />
      <el-table-column prop="courseIntroduce" label="课程简介" show-overflow-tooltip />
      <el-table-column prop="applicablePopulation" label="适用人群" />
      <el-table-column prop="typeId" label="课程分类" #default="scope">
        <el-tag>{{ getCourseTypeName(scope.row.typeId) }}</el-tag>
      </el-table-column>
      <el-table-column prop="teacherId" label="咨询师" #default="scope">
        <el-tag>{{ getConsultName(scope.row.teacherId) }}</el-tag>
      </el-table-column>
      <!--      <el-table-column prop="courseVideo" label="课程视频" >-->
      <!--        <template #default="scope">-->
      <!--          <video controls width="220" height="140"  :key="scope.row.courseVideo">-->
      <!--            <source :src="'http://localhost:8888/downLoad?filename='+scope.row.courseVideo" />-->
      <!--          </video>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column prop="learnHarvest" label="学习收获" show-overflow-tooltip />
      <el-table-column width="180" label="操作">
        <template #default="scope">
          <el-button size="mini" icon="el-icon-edit" type="primary" @click="updateCourse(scope.row)">编辑</el-button>
          <el-button size="mini" icon="el-icon-delete" type="danger" @click="deleteCourse(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="queryInfo.pageNum" :page-sizes="[1, 5, 10, 15, 20]" :page-size="queryInfo.pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>



    <!-- 新增和修改的对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="cancle">
      <el-form :model="course">
        <el-form-item label="课程名称" label-width="80px">
          <el-input placeholder="请输入课程名称" v-model="course.courseName"></el-input>
        </el-form-item>
        <el-form-item label="课程图片" label-width="80px">
          <!-- el-upload:上传组件
          action:选择图片是上传的接口
          List-type: 上传组件的类型
          on-success:上传成功的回调函数
          Limit: 限制只能上传一个文件
          on-preview:图片预览的事件
          on-remove:删除图片的事件 -->
          <el-upload :action="url + 'upload'" list-type="picture-card" :on-success="handleSuccess" :limit="1"
            :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :file-list="fileList">
            <i class="el-icon-plus"></i>
          </el-upload>
          <!-- 预览图片 -->
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="课程时长" label-width="80px">
          <el-input placeholder="请输入课程时长" v-model="course.couseTime"></el-input>
        </el-form-item>
        <el-form-item label="课程数量" label-width="80px">
          <el-input placeholder="请输入课程数量" v-model="course.courseMount" />
        </el-form-item>
        <el-form-item label="课程简介" label-width="80px">
          <el-input placeholder="请输入课程简介" v-model="course.courseIntroduce" />
        </el-form-item>
        <el-form-item label="适用人群" label-width="80px">
          <el-input placeholder="请输入适用人群" v-model="course.applicablePopulation" />
        </el-form-item>
        <el-form-item label="课程分类" label-width="80px">
          <!--          <el-input placeholder="请输入课程分类" v-model="course.typeId"/>-->
          <el-select v-model="course.typeId" placeholder="请选择">
            <el-option v-for="item in courseTypeList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="咨询师" label-width="80px">
          <!--          <el-input placeholder="请输入咨询师" v-model="course.teacherId"/>-->
          <el-select v-model="course.teacherId" placeholder="请选择">
            <el-option v-for="item in consultList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程视频" label-width="80px">
          <el-upload :action="url + 'upload'" :file-list="videoList" :on-success="handleVideoSuccess" :limit="1"
            :on-remove="handleVideoRemove">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="学习收获" label-width="80px">
          <el-input placeholder="请输入学习收获" v-model="course.learnHarvest" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import { url } from '@/util/tools.js'
export default {
  data() {
    return {
      url: '',
      // 查询信息对象
      queryInfo: {
        courseName: '',
        typeId: '',
        teacherId: '',
        pageNum: 1,
        pageSize: 5
      },
      total: 0,
      courseList: [],
      title: '', // 对话框标题
      dialogFormVisible: false, // 是否显示对话框
      course: {
        id: '',
        courseName: '',
        tabularChart: '',
        couseTime: '',
        courseMount: '',
        courseIntroduce: '',
        applicablePopulation: '',
        typeId: '',
        teacherId: '',
        learnHarvest: '',
        courseVideo: ''
      },
      dialogVisible: false,
      dialogImageUrl: '',
      fileList: [],
      courseTypeList: [],
      consultList: [],
      videoList: []
    }
  },
  methods: {

    handleVideoSuccess(response) {
      // 把上传后的图片路径，交给文章对象的img
      this.course.courseVideo = response.message;
    },

    // 删除文件的事件
    handleVideoRemove(file, fileList) {
      // console.log(file, fileList);
      // 移除数据
      this.course.courseVideo = '';
    },



    addCourse() {
      this.title = "新增课程";
      this.dialogFormVisible = true
    },


    // 添加/修改心理知识
    add() {
      if (this.title === '新增课程') {
        this.$http({
          method: "POST",
          url: 'course/save',
          data: this.course
        }).then(res => {
          if (res.data.status === 200) {
            this.$message.success("添加成功")
            this.courseIsNull()
            this.dialogFormVisible = false
            this.queryList()
          } else {
            this.$message.error("添加失败")
          }
        })
      } else if (this.title === '更新课程') {
        this.$http({
          method: "PUT",
          url: 'course/update',
          data: this.course
        }).then(res => {
          if (res.data.status === 200) {
            this.$message.success("更新成功")
            this.courseIsNull()
            this.dialogFormVisible = false
            this.queryList()
          } else {
            this.$message.error("更新失败")
          }
        })
      }
      this.fileList = []
      this.videoList = []
    },
    cancle() {
      this.dialogFormVisible = false
      this.courseIsNull()
      this.queryList()
    },




    // 处理上传成功的函数
    handleSuccess(response) {
      // 把上传后的图片路径，交给文章对象的tabularChart
      this.course.tabularChart = response.message;
    },

    // 删除图片的事件
    handleRemove(file, fileList) {
      console.log(file, fileList);
      // 移除数据
      this.course.tabularChart = '';
    },

    // 预览图片事件
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },


    updateCourse(row) {
      this.title = "更新课程"
      this.course = row
      this.dialogFormVisible = true
      this.fileList = [{
        name: row.tabularChart,
        url: url + 'downLoad?filename=' + row.tabularChart
      }];
    },


    deleteCourse(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then().then(() => {
        this.$http.delete('course/delete/' + id).then((resp) => {
          if (resp.data.status == 200) {
            this.$message.success(resp.data.message);
            this.queryInfo.pageNum = 1
            this.queryList();
          } else {
            this.$message.error("关联其他数据，不允许删除");
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },



    queryList() {
      if (this.queryInfo.courseName !== '') {
        this.queryInfo.pageNum = 1
      }
      this.$http.get('course/page', {
        params: this.queryInfo
      }).then(res => {
        if (res.data.status == 200) {
          this.courseList = res.data.data.list;
          this.total = res.data.data.total
          console.log(res)
        } else {
          this.$message.error('查询失败!')
        }
      })
    },
    // 设置heartknowledge为Null
    courseIsNull() {
      this.course = {
        id: '',
        courseName: '',
        tabularChart: '',
        couseTime: '',
        courseMount: '',
        courseIntroduce: '',
        applicablePopulation: '',
        typeId: '',
        teacherId: '',
        learnHarvest: '',
      }
      this.fileList = [];
    },
    handleSizeChange(size) {
      // console.log('每页显示数量发生改变');
      this.queryInfo.pageSize = size
      this.queryInfo.pageNum = 1
      this.queryList()
    },
    handleCurrentChange(num) {
      // console.log('页码发生改变');
      this.queryInfo.pageNum = num
      this.queryList()
    },
    queryCourseTypeList() {
      this.$http.get("coursetype/findAll").then((res) => {
        if (res.data.status == 200) {
          this.courseTypeList = res.data.data
        }
      })
    },
    queryConsultList() {
      this.$http.get("consult/getIdAndName").then((res) => {
        if (res.data.status == 200) {
          this.consultList = res.data.data
        }
      })
    },

    getCourseTypeName(typeId) {
      // console.log(typeId)
      for (let i = 0; i < this.courseTypeList.length; i++) {
        if (this.courseTypeList[i].id == typeId) {
          // console.log(this.typeList[i].typeName)
          return this.courseTypeList[i].name
        }
      }
    },

    getConsultName(teacherId) {
      // console.log(typeId)
      for (let i = 0; i < this.consultList.length; i++) {
        if (this.consultList[i].id == teacherId) {
          // console.log(this.typeList[i].typeName)
          return this.consultList[i].name
        }
      }
    },

  },
  mounted() {
    this.queryList();
    this.queryCourseTypeList()
    this.queryConsultList()
    // 动态的获取tool.js中的url，并赋值给当前组件的全局url
    this.url = url;
  }
}
</script>
<style>
.el-breadcrumb {
  margin-bottom: 15px;
  padding: 0 0 15px;
  border-bottom: 1px solid #ddd;
}

.el-pagination {
  margin-top: 15px;
}

.el-link {
  padding: 0 5px;
}

/**设置富文本编辑器的最小高度，注意style中不能使用scoped **/
.ql-container {
  min-height: 200px;
}
</style>
